<template>
	<div class="survey_form_wrapper" v-loading="loading">
		<template v-if="surveyData.del === '1'">
			<template v-if="isAnswer === '1'">
				<div class="finish">
					<i class="el-icon-sw-smiling-face"></i>
					<p>您已完成问卷调查答题, 如若想重新答题，请点击重新答题按钮</p>
					<el-button type="primary" size="small" @click="handleNewlyAnswer">重新答题</el-button>
				</div>
			</template>
			<template v-else>
				<div class="title">{{ surveyData.title }}</div>
				<div class="content">
					<el-form ref="surveyForm">
						<topic-item v-for="(item, index) in surveyData.topics" :key="index" :class="{ error: indexArr.indexOf(index) !== -1 }" :data="item"></topic-item>
					</el-form>
				</div>
				<div class="button"><el-button type="primary" @click="handleSubmitForm">提交</el-button></div>
			</template>
		</template>
		<template v-else>
			<div class="disabled"><el-empty description="当前问卷调查未开启"></el-empty></div>
		</template>
	</div>
</template>

<script>
import topicItem from './topic';
import { getSurveyData } from '@/api/web/tbQuestionnaireInfo';
import { submitSurveyAnswer } from '@/api/web/tbStudentQuestionnaireInfo';
const multiIndex = (arr) => {
	let idxs = [];
	arr.forEach((item, index) => {
		if (!item || item.length === 0 || Object.keys(item).length === 0) {
			idxs.push(index);
		}
	});
	return idxs;
};
export default {
	components: { topicItem },
	data() {
		return {
			indexArr: [],
			surveyData: {},
			subjectData: [],
			loading: false,
			isAnswer:  '0'
		};
	},
	computed: {
		surveyId() {
			return this.$route.query.id;
		},
		answerArr() {
			return this.surveyData.topics;
		}
	},
	watch: {
		surveyId: {
			async handler(val) {
				this.loading = true;
				await this.getSurveyInfoData();
				this.loading = false;
			},
			immediate: true
		}
	},
	mounted() {
		var isAnswer= (this.$local.get('isAnswer')+"").split(",");
		isAnswer.forEach(item=>{
			if(item==this.$route.query.id){
				this.isAnswer="1";
			}
		})
	},
	methods: {
		//获取问卷数据
		async getSurveyInfoData() {
			let result = await getSurveyData(this.surveyId).then((res) => res.data);
			if (result.code === '0') {
				let datas = !result.data ? {} : { ...result.data[0] };
				this.surveyData = { id: datas.id, del: datas.del, title: datas.title };
				this.subjectData = datas.contentList;
				console.log(this.subjectData);
				this.$set(this.surveyData, 'topics', this.formatSubjectData(datas.contentList));
			}
		},

		//格式化题目数据
		formatSubjectData(arr) {
			return arr.map((item) => {
				let obj = { id: item.id, title: item.content, type: parseInt(item.type), answer: item.type !== '2' ? '' : [] };
				let optArr = Object.keys(item).filter((v) => v.indexOf('questionOption') !== -1);
				obj['option'] = [];
				optArr.forEach((v) => {
					obj['option'].push(item[v]);
				});
				return obj;
			});
		},

		//提交问卷
		handleSubmitForm() {
			let that = this;
			let isAnswer = this.answerArr.every((item) => !!item.answer && item.answer.length > 0);
			this.indexArr = [];
			if (!isAnswer) {
				this.$confirm('您还未答完所有题目，是继续答题还是直接提交答案?', '提示', {
					confirmButtonText: '提交答案',
					cancelButtonText: '继续答题',
					type: 'warning',
					closeOnClickModal: false,
					async beforeClose(action, instance, done) {
						if (action === 'confirm') {
							instance.confirmButtonLoading = true;
							await that.submitAnswerRequest();
							instance.confirmButtonLoading = false;
							done();
						} else if (action === 'cancel') {
							that.indexArr = multiIndex(that.answerArr.map((item) => item.answer));
							done();
						}
					}
				}).catch(() => {});
			} else {
				this.submitAnswerRequest();
			}
		},

		//提交请求参数
		formatSubmitParams() {
			let params = {};
			params['obj'] = { questionId: this.surveyData.id, courseId: '999', del: 1, isSubmit: 1 };
			params['list'] = this.answerArr.map((item) => {
				let info = this.subjectData.find((v) => v.id === item.id);
				info['contentId'] = info.id;
				info['answer'] = Array.isArray(item.answer) ? item.answer.join() : item.answer;
				return info;
			});
			return params;
		},

		//提交答案请求
		async submitAnswerRequest() {
			let params = this.formatSubmitParams();
			let result = await submitSurveyAnswer(params).then(res => res.data);
			if (result.code === '0') {
				this.$message.success('问卷回答完成');
				let params = this.formatSubmitParams();
				this.$local.set('isAnswer', this.$local.get('isAnswer')+","+params.obj.questionId);
				this.isAnswer = '1';
			}
		},

		//重新答题
		async handleNewlyAnswer() {
			this.isAnswer = '0';
			// this.$local.remove('isAnswer');
		}
	}
};
</script>

<style lang="scss" scoped>
.survey_form_wrapper {
	flex: 1;
	background-color: #fff;
	margin-bottom: 48px;
	padding: 40px;
	border-radius: 6px;
	.title {
		font-size: 24px;
		font-weight: bold;
		text-align: center;
		margin-bottom: 20px;
	}
	.button {
		margin-top: 30px;
		text-align: center;
		.el-button {
			width: 180px;
			font-size: 20px;
			padding: 15px;
			border-color: #357c65;
			background-color: #357c65;
			&:hover {
				background-color: #459f82;
			}
		}
	}
	.finish {
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		height: 100%;
		i {
			font-size: 144px;
			opacity: 0.15;
		}
		p {
			font-size: 18px;
			margin: 30px 0;
		}
		button {
			border-color: #357c65;
			background-color: #357c65;
			&:hover {
				background-color: #459f82;
			}
		}
	}
	.disabled {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}
}
</style>
